#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/20 16:48
@desc
"""
from impala.error import HiveServer2Error
from impala.dbapi import connect


class PyHiveOpr:

    def __init__(self, host='10.231.32.131', port=10000, database='sjtd', auth_mechanism='GSSAPI',
                 kerberos_service_name='hive'):
        """
        创建PyHiveOpr连接，并获取Connect对象 和 cursor对象
        :param host:
        :param port:
        :param database:
        :param auth_mechanism:
        :param kerberos_service_name:
        """
        self.hiveConn = connect(host=host, port=port, database=database, auth_mechanism=auth_mechanism,
                                kerberos_service_name=kerberos_service_name)
        self.cursor = self.hiveConn.cursor()

    def __del__(self):
        """
        析构对象
        :return: PyHiveOpr
        """
        self.cursor.close()
        self.hiveConn.close()

    def isHiveTableExists(self, tablename, databasename):
        """
        获取表是否存在
        :param table_name:
        :return: boolean
        """
        return self.cursor.table_exists(tablename, databasename)

    def create(self, sql):
        """
        创建表的SQL
        :param sql:
        :return:
        """
        sql = sql.encode('utf-8')
        ret = False
        try:
            self.cursor.execute(sql)
            results = self.cursor.status()
            ret = True if results == 'FINISHED_STATE' else False
        except Exception as e:
            print(e)
            print(e.message)
            pass
        return ret

    def drop(self, sql):
        """
        删除表
        :param sql:
        :return:
        """
        ret = False
        try:
            self.cursor.execute(sql)
            results = self.cursor.status()
            ret = True if results == 'FINISHED_STATE' else False
        except Exception as e:
            pass
        return ret

    def fetchrow(self, sql):
        """
        获取记录，如果失败，返回空List
        :param sql:
        :return: list
        """
        lst = []
        try:
            self.cursor.execute(sql)
            lst = self.cursor.fetchall()
        except Exception:
            pass
        return lst

    def execsql(self, sql):
        """
        执行增删改操作
        :param sql:
        :return:
        """
        try:
            self.cursor.execute(sql)
            # 得到执行语句的状态
            status = self.cursor.status()
            if status == 'FINISHED_STATE':
                self.hiveConn.commit()
            else:
                self.hiveConn.rollback()
        except Exception as e:
            status = False
        return status


if __name__ == '__main__':
    pyo = PyHiveOpr()
    ret =pyo.create("CREATE TABLE sjtd.tmp_crawl_fangtianxia_test_txt\n(taskid VARCHAR(64)\n\t,url VARCHAR(1024)\n\t,result BINARY\n\t,updatetime DOUBLE)\n ROW  FORMAT DELIMITED FIELDS TERMINATED BY '\\t' STORED AS TEXTFILE")
    print(ret)
